import json
from scopt.util import message as msg_util
from scopt.util.validation import _jsonify


def mpu_list_init(data_packet, name):
    if not 'response' in data_packet['message']:
        response = {'resh': {'status': 'OK'},
                    'resd': [{'id': 'scopt',
                              'type': 'root',
                              'name': 'scopt'}]}
        data_packet['message']['response'] = response

    return mpu_list_append(data_packet,
                                name,
                                'module',
                                name.replace('scopt.mpu.', ''),
                                'scopt')


def mpu_list_append(data_packet, node_id, node_type, name, node_parent):
    resd = msg_util.get_response_data(data_packet)
    resd.append({'id': node_id,
                 'type': node_type,
                 'name': name,
                 'parent': node_parent})
    return data_packet


def mpu_get(data_packet, handler):
    response = {'resh': {'status': 'OK'},
                'resd': {'message_type': handler.TYPE,
                         'version': handler.VERSION,
                         'request': json.dumps(handler.REQUEST(),
                                               default=_jsonify(handler.TYPE),
                                               indent=2),
                         'response': json.dumps(handler.RESPONSE(),
                                                default=_jsonify(handler.TYPE),
                                                indent=2),
                         'doc': _('{}.{}.doc'.format(handler.TYPE, 
                                                     handler.VERSION))}}
    data_packet = msg_util.set_response(data_packet, response)
    return msg_util.finish_data_packet(data_packet)
